package kz.kstu.scantest.desktop.ui.dialog;

import kz.kstu.scantest.app.delegate.api.AccountDelegate;
import kz.kstu.scantest.app.delegate.impl.AccountDelegateImpl;
import kz.kstu.scantest.business.entity.security.Account;
import kz.kstu.scantest.business.util.DigestUtil;
import kz.kstu.scantest.desktop.util.GUIUtils;
import org.apache.log4j.Logger;

import javax.security.auth.login.LoginException;
import javax.swing.*;
import java.awt.event.*;
import java.security.NoSuchAlgorithmException;

public class LoginDialog extends JDialog {

    public static final Logger LOGGER = Logger.getLogger(LoginDialog.class);

    private static final int WIDTH = 300;
    private static final int HEIGHT = 200;
    private static final String CHANGE_PASSWORD_LABEL = "Сменить пароль";
    private static final String LOGIN_TITLE = "Авторизация";
    private static final String INCORRECT_LOGIN_OR_PASSWORD = "Логин и/или пароль указан неверно";

    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField loginField;
    private JLabel changePasswordLabel;
    private JPasswordField passwordField;
    private Account account;

    public LoginDialog() {
    }

    public Account login() {
        initStaticComponents();
        return account;
    }

    private void initStaticComponents() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        setSize(WIDTH, HEIGHT);
        initListeners();
        GUIUtils.centerAndShow(this);
    }

    private void initListeners() {

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onCancel();
                    }
                }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        changePasswordLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                ChangePasswordDialog changePasswordDialog = new ChangePasswordDialog();
                changePasswordDialog.changePassword();
            }
        });

    }

    private void onOK() {
// add your code here

        AccountDelegate accountDelegate = new AccountDelegateImpl();
        String password = new String(passwordField.getPassword());
        try {
            String encryptPassword = DigestUtil.digest(password, DigestUtil.ALGORITHM_SHA);
            account = accountDelegate.login(loginField.getText(), encryptPassword);
            dispose();
        } catch (LoginException e) {
            JOptionPane.showMessageDialog(this, INCORRECT_LOGIN_OR_PASSWORD, LOGIN_TITLE, JOptionPane.ERROR_MESSAGE);
        } catch (NoSuchAlgorithmException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), LOGIN_TITLE, JOptionPane.ERROR_MESSAGE);
            LOGGER.error(e.getMessage(), e);
        }
    }

    private void onCancel() {
// add your code here if necessary
        dispose();
    }

    private void createUIComponents() {
        changePasswordLabel = new JLabel(CHANGE_PASSWORD_LABEL);
    }
}
